package com.example.brazil_project.function;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import com.example.brazil_project.ClippingPhotoActivity;
import com.example.brazil_project.DucumentActivity;
import com.example.brazil_project.IndexActivity;
import com.example.brazil_project.MainActivity;
import com.example.brazil_project.parameter.Parameter;
import com.example.brazil_project.util.StringUtils;
import com.example.brazil_project.util.jsonUtil;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.webkit.WebView;

public class PhotoFunction {
	Activity mContxt;  
	Object view ;
	WebView webview =null;
	public static int x =1; //长比例
	public static int y= 1;//宽比例
	 public PhotoFunction(Activity mContxt,Object view) {  
	        this.mContxt = mContxt;  
	        this.view = view;
	        webview = (WebView) view;
	       
	  }  
	 public static String Photoname = "";
	
	 /**
	  * 调用照相机
	  */
	public void gotoPhoto(){	
		Parameter.intiphoto();
		Photoname = Parameter.getPhotoName();
		Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);				
		File f = new File(mContxt.getExternalCacheDir(),Photoname+".jpg");
		File af = new File(mContxt.getExternalCacheDir(),Photoname+"1.jpg");
		intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		mContxt.startActivityForResult(intentCamera, Parameter.gotophoto);
		Parameter.initPhoto = f.toString();
		Parameter.afterPhoto=af.toString();
	}
	
	/**
	 * 从相册里面挑选图片
	 */
	 
	public String getPhoto(){
		Parameter.intiphoto();
		// 从相簿中获得照片
		
		Intent mIntent = new Intent(Intent.ACTION_GET_CONTENT);
		mIntent.putExtra("crop", "true");
		mIntent.addCategory(Intent.CATEGORY_OPENABLE);
		mIntent.setType("image/*");
		mContxt.startActivityForResult(mIntent, Parameter.getphoto);
		return null;
		
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		
		
			
			
//				//如果没有放回值
//				if((resultCode != Activity.RESULT_OK||Parameter.initPhoto.length()<=0)&&requestCode!=Parameter.clippinphotopage&&requestCode!=Parameter.getphoto)
//					return;
				 
				// 从相机中返回的照片	
				if (requestCode ==  Parameter.gotophoto) { 
					Intent mIntent = new Intent(mContxt,ClippingPhotoActivity.class);
					mContxt.startActivityForResult(mIntent, Parameter.clippinphotopage);
					
				}
				// 从相册中返回的照片	
				if (requestCode ==  Parameter.getphoto) {
			
					Parameter.intiphoto();
					if(data==null){
						webview.loadUrl("javascript:setimg('')");
						return;
					}
					Uri uri= data.getData(); // 返回的是一个Uri
					if(uri==null){
						uri = Uri.parse(data.getAction());
					}
					ContentResolver resolver = mContxt.getContentResolver();
					Bitmap  bm =null;
					try {
						  //把uri 转出bitmap 然后写来临时文件
						  bm = MediaStore.Images.Media.getBitmap(resolver, uri);
						  Photoname = Parameter.getPhotoName();
						  File f = new File(mContxt.getExternalCacheDir(),Photoname+".jpg");
						  File af = new File(mContxt.getExternalCacheDir(),Photoname+"1.jpg");
						  Parameter.initPhoto = f.toString();
						  Parameter.afterPhoto=af.toString();	
						  BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
						  bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
		                    bos.flush();
		                    bos.close();
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 
					Intent mIntent = new Intent(mContxt,ClippingPhotoActivity.class);
					mContxt.startActivityForResult(mIntent, Parameter.clippinphotopage);
					
					
				}
				//处理完图片
				if (requestCode ==  Parameter.clippinphoto) { 			
					mContxt.finish();
				}
				//返回拍照或者打开相册的地方的地方
				if (requestCode ==  Parameter.clippinphotopage) { 
				
					if(!StringUtils.isBlank(Parameter.afterPhoto)){
						webview.loadUrl("javascript:setimg('"+Parameter.afterPhoto+"')");
					}	
					
				}
		
		
	}
	
	/**
	 * 图像剪裁
	 * @param uri		原始图片uri
	 * @param outuri	输出的图片uri
	 * @param outuri	剪切比例x轴
	 * @param outuri	剪切比例y轴
	 * @param requestCode 
	 */
	public void cropImageUri(Uri uri,Uri outuri, int requestCode,int x ,int y){
		this.x =1; //长比例
		this.y= 1;//宽比例
		//截图工具
		 Intent intent = new Intent("com.android.camera.action.CROP");
		 intent.setDataAndType(uri, "image/*");
		 intent.putExtra("crop", "true");
		 //限制比例
		 intent.putExtra("aspectX", x);
		 intent.putExtra("aspectY", y);
//		 //限制大小
//		 intent.putExtra("outputX", 200);
//		 intent.putExtra("outputY", 400);
//	
		 intent.putExtra("scale", true);
		 intent.putExtra(MediaStore.EXTRA_OUTPUT, outuri);
		 intent.putExtra("return-data", false);
		 intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		 intent.putExtra("noFaceDetection", true); // no face detection		
		 mContxt.startActivityForResult(intent, requestCode);
	}
	//图像剪裁
	public void cropImageUri(String  x1 ,String y1){
		int x = 1;
		int y = 1;
		if(x1!=null&&x1.length()>0){
			x = Integer.parseInt(x1);
		}
		if(y1!=null&&y1.length()>0){
			y = Integer.parseInt(y1);
		}
		
		//获取编辑图片地址
		File fin =  new File( Parameter.initPhoto);
		//获取编辑后输出图片地址
		File fio =  new File( Parameter.afterPhoto);
		cropImageUri(Uri.fromFile(fin), Uri.fromFile(fio),  Parameter.clippinphoto,x,y);	
	}
	/**
	 * 剪切页面获取需要处理前的图片
	 */
	public String getintiimg(){
		return Parameter.initPhoto;
		
		
	}
	/**
	 * 剪切页面获取处理后的图片
	 */
	public String getafterimg(){
		return Parameter.afterPhoto;
		
		
	}
	
	/**
	 * 通过URl转换绝对路径
	 */
	public String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = mContxt.managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
      
        return cursor.getString(column_index);
    }
	
	
	//设置长宽
	public void setXY(String x,String y){
		this.x= Integer.parseInt(x);
		this.y= Integer.parseInt(y);
	}
	
	//获取长宽
		public String getXY(){
			Map m =  new HashMap();
			m.put("x", this.x);
			m.put("y", this.y);
			String json = jsonUtil.getJsonbymap(m);
			return json;
		}
		
	

    public String getImagePathFromUri(Uri fileUrl)

    {

       String fileName = null;

       Uri filePathUri = fileUrl;

       if (fileUrl != null)

       {

           if (fileUrl.getScheme().toString().compareTo("content") == 0)

           {

               // content://开头的uri

              Cursor cursor = mContxt.getContentResolver().query(fileUrl, null, null, null, null);

              if (cursor != null && cursor.moveToFirst())

              {

                  int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

                  fileName = cursor.getString(column_index); // 取出文件路径

 

                  // Android 4.1 更改了SD的目录，sdcard映射到/storage/sdcard0

                  if (!fileName.startsWith("/storage") && !fileName.startsWith("/mnt"))

                  {

                     // 检查是否有”/mnt“前缀

                     fileName = "/mnt" + fileName;

                  }

                  cursor.close();

              }

           }

           else if (fileUrl.getScheme().compareTo("file") == 0) // file:///开头的uri

           {

              fileName = filePathUri.toString();// 替换file://

              fileName = filePathUri.toString().replace("file://", "");
 int index = fileName.indexOf("/sdcard");
 fileName  = index == -1 ? fileName : fileName.substring(index);

 

             

              if (!fileName.startsWith("/mnt"))

              {

                  // 加上"/mnt"头

                  fileName += "/mnt";

              }

           }

    }

       return fileName;

    }
	
	
}
